package com.xuecheng.content.config;

import com.xuecheng.common.domain.uaa.LoginUser;
import com.xuecheng.common.util.SecurityUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;


@Configuration
public class GuliFeignConfig {
 
    /**
     * 解决fein远程调用丢失请求头
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {

   /*             HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
                String jsonToken = request.getHeader(LoginUser.GATEWAY_JSON_TOKEN);

                template.header("Authorization",jsonToken);*/

                // 1、RequestContextHolder 拿到当前的请求
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    // 原始请求 页面发起的老请求
                    HttpServletRequest request = attributes.getRequest();
                    if (request != null) {
                        // 获取原始请求的头数据 cookie
                        String Authorization = request.getHeader("Authorization");
 
                        // 给feign生成的心请求设置请求头cookie
                        template.header("Authorization", Authorization);
                    }
                }
            }
        };
    }
}
